package models

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
	"xinhua_bookstore_db/appconfig"
)

var DB *gorm.DB

func Init() {
	var err error
	mysqlConf := appconfig.AppConf.Mysql
	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		mysqlConf.User, mysqlConf.Password, mysqlConf.Host, mysqlConf.Port, mysqlConf.Database)

	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
	}
	//日志打印
	log.Println("MySQL连接成功")
	//数据表迁移
	DB.AutoMigrate(&User{}, &Books{}, &Collect{})
	log.Println("数据库表迁移成功")
}
